package com.guaoran.wechat.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;

/**
 * @author : 孤傲然
 * @Description :
 *  微信功能：使用第三方sdk方式
 * @date :2018/1/13 16:34
 */
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
    @Autowired
    private WxMpService wxMpService;
    /*获取域名+项目名*/
    @Value("${domainName}")
    private String domainName;
    /*获取微信授权认证后重定向的url地址*/
    @Value("${wechat.authorize.redirectURL}")
    private String redirectURL;
    /*遇到多个域名都需要授权的时候的跳转授权域名*/
    @Value("${wechat.anotherAuthorizedDomainName}")
    private String anotherAuthorizedDomainName;

    /**
     * 组装网页授权url，然后构成超链接让用户点击进行授权的链接
     * //http://guaoran.nat300.top/springboot/wechat/authorize?returnUrl=http://www.baidu.com
     * @param returnUrl：最后返回到的url地址
     * @return
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        log.info("authorize...param:returnUrl={}",returnUrl);
        boolean flag = false;
        try {
            //判断有没有传认证后重定向的url，没有则使用默认的
            if (returnUrl == null || "".equals(returnUrl)) {
                returnUrl = redirectURL;
            }
            returnUrl = redirectURL;
            //获得用户授权后信息的url地址
            String getUserInfoURL = domainName + "/wechat/getUserInfo";
            //1.首先构造网页授权url，然后构成超链接让用户点击：
            String getUserRedirectURL = wxMpService.oauth2buildAuthorizationUrl(getUserInfoURL, WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl, "utf-8"));
            if(!flag){
                //此方法是由于授权域名只能是一个，因此只能进行跳转方式进行操作，详情参考https://github.com/HADB/GetWeixinCode
                /*//步骤1.在该域名下放置get-weixin-code.html文件，
                //步骤2.拼接url地址
                getUserRedirectURL = anotherAuthorizedDomainName + "?appid=wx64274a7212f360a7&redirect_uri=http%3A%2F%2Fguaoran.s1.natapp.cc%2Fspringboot%2Fwechat%2FgetUserInfo&response_type=code&scope=snsapi_userinfo&state=http://www.baidu.com#wechat_redirect";
                */
                getUserRedirectURL = anotherAuthorizedDomainName + getUserRedirectURL.substring(getUserRedirectURL.indexOf("?"));
            }

            log.info("authorize..getUserRedirectURL=" + getUserRedirectURL);
            return "redirect:" + getUserRedirectURL;
        } catch (Exception e) {
            log.error("authorize...Exception:" + e.toString(), e);
        }
        return null;
    }
    //xxx/get-weixin-code.html
    /**
     * 获取access_token进而获取用户信息，
     * @param code
     * @param state
     *   xxx/get-weixin-code.html
     * @return
     */
    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestParam("code") String code,@RequestParam("state") String state){
        log.info("getUserInfo...param:code={},state={}",code,state);
        try {
            //2.当用户同意授权后，会回调所设置的url并把authorization code传过来，然后用这个code获得access_token，其中也包含用户的openid等信息
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            log.info("getUserInfo...wxMpOAuth2AccessToken={}",wxMpOAuth2AccessToken.toString());
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
            log.info("getUserInfo...wxMpUser={}",wxMpUser.toString());
            String openId = wxMpUser.getOpenId();
            return "redirect:" + state+"?openid="+openId;
        } catch (Exception e){
            log.error("getUserInfo...Exception:"+e.toString(),e);
        }
        return null;
    }

}
